package com.gitee.chili.leisure.game;

import cn.hutool.core.util.ReflectUtil;
import com.gitee.chili.leisure.SingletonFactory;
import com.gitee.chili.leisure.exception.BusinessException;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * PlayerFactory
 *
 * @author week solider
 * @since 2020-07-30
 */
public class PlayerFactory extends SingletonFactory<Player> {

    private static final Map<Long, Class<? extends Player>> PLAYERS = new ConcurrentHashMap<>();


    public PlayerFactory(Player instance, Supplier<? extends Player> factory) {
        super(instance, factory);
    }

    /**
     * 注册游戏类型玩家实例
     *
     * @param mode  游戏类型
     * @param clazz 实例对象地址
     */
    public static void register(Long mode, Class<? extends Player> clazz) {
        PLAYERS.put(mode, clazz);
    }

    /**
     * 创建一个游戏类型实例
     *
     * @param gameMode 需要创建的游戏类型
     * @param <T>      实例
     */
    @SuppressWarnings("unchecked")
    public static <T extends Player> T getInstant(Long gameMode) {

        Class<? extends Player> clazz = PLAYERS.get(gameMode);

        if (Objects.isNull(clazz)) {

            if (gameMode == 1) {
                return (T) of(MahjongPlayer::new).obtain();
            } else if (gameMode == 2) {
                return (T) of(PokerPlayer::new).obtain();
            } else {
                throw new BusinessException("游戏类型未找到, 创建实例失败");
            }
        }

        return (T) ReflectUtil.newInstance(clazz);
    }
}
